<template>
  <div style="padding: 10px 15px">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="请输入用户名称"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <el-select
        v-if="this.logincpnid == 'system'"
        v-model="selectparms.cpnID"
        filterable
        clearable
        class="filter-item"
        placeholder="请选择企业"
        :filter-method="cpnmatch"
         @clear="cpnmatch"
      >
        <el-option
          v-for="item in cpnoptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span v-html="item.label" />
        </el-option>
      </el-select>
      <el-button
        class="filter-item seachbttn"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >查询</el-button
      >
    </div>
    <div
      class="filter_fenge"
      style="border: none; border-top: 1px solid #d1ddeb"
    />
    <div class="filter-container">
      <el-button
        class="filter-item bttnleft"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
        >新增</el-button
      >
      <el-button
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        @click="deleteClick()"
        >删除</el-button
      >
    </div>
    <!--table-->
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="MngrbaseinfoData"
      fit
      highlight-current-row
      style="width: 100%"
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="企业名称" align="left" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.cpnIDStr }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录名" align="left" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.loginName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="昵称" align="left" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.nickName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上次登录IP" align="left" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.lastLoginIP }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本次登录IP" align="left" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.thisLoginIP }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后一次登录" align="left" min-width="160px">
        <template slot-scope="{ row }">
          <span>{{ row.lastLoginTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="拥有角色" align="left" min-width="250px">
        <template slot-scope="{ row }">
          <span>{{ row.mangerRoles }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="380">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleClick(scope.row, 1)"
            >修改信息</el-button
          >
          <el-button
            v-if="loginid != scope.row.id"
            type="primary"
            size="mini"
            @click="handleClick(scope.row, 2)"
            >修改角色</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleClick(scope.row, 3)"
            >修改密码</el-button
          >
          <el-button type="danger" size="mini" @click="deleteClick(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <span style="color: red">注:当前用户无法修改角色</span>
    <pagination
      v-show="listQuery.total > 0"
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData(this)"
    />

    <!--table-->
    <!--弹出层 添加用户模块-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="60%"
      :before-close="handleClose"
      :show-close="false"
    >
      <el-form :model="form" :inline="true" label-position="right">
        <el-form-item
          label="登录名称"
          prop="loginName"
          :rules="[
            { required: true, message: '登录名称不能为空', trigger: 'blur' },
          ]"
        >
          <el-input v-model="form.loginName" />
        </el-form-item>
        <el-form-item
          label="员工账户(昵称)"
          prop="nickName"
          :rules="[
            { required: true, message: '员工账户不能为空', trigger: 'blur' },
          ]"
        >
          <el-input v-model="form.nickName" />
        </el-form-item>
        <el-form-item
          label="登录密码"
          prop="passWord"
          :rules="[
            { required: true, message: '登录密码不能为空', trigger: 'blur' },
          ]"
        >
          <el-input v-model="form.passWord" type="Password" />
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="newpassWord"
          :rules="[
            { required: true, message: '密码不能为空', trigger: 'blur' },
          ]"
        >
          <el-input v-model="form.newpassWord" type="Password" />
        </el-form-item>
        <el-form-item label="企业">
          <el-select
            v-model="form.cpnId"
            clearable
            filterable
            class="filter-item"
          >
            <el-option
              v-for="item in cpnoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <span v-html="item.label" />
            </el-option>
          </el-select>
        </el-form-item>
        <br />
        <el-form-item
          label="角色"
          prop="roleName"
          :rules="[
            { required: true, message: '密码不能为空', trigger: 'change' },
          ]"
        >
          <el-checkbox
            v-for="role in rolelist"
            :key="role.id"
            v-model="role.ischeck"
            :label="role.roleName"
            @change="rolechange($event, role.id)"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveForm(0)">确 定</el-button>
      </div>
    </el-dialog>

    <!--弹出层 修改信息-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogInfoVisible"
      width="60%"
      :before-close="handleClose"
      :show-close="false"
    >
      <el-form :model="form" :inline="true" label-position="right">
        <el-form-item label="登录名称">
          <el-input v-model="form.loginName" />
        </el-form-item>
        <el-form-item label="员工账户(昵称)">
          <el-input v-model="form.nickName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogInfoVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveForm(1)">确 定</el-button>
      </div>
    </el-dialog>

    <!--弹出层 修改密码-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogPawssdVisible"
      width="60%"
    >
      <el-form :model="form" :inline="true" label-position="right">
        <el-form-item label="登录名称">
          <span readonly v-html="form.loginName" />
        </el-form-item>
        <el-form-item label="员工账户(昵称)">
          <span readonly v-html="form.nickName" />
        </el-form-item>
        <el-form-item label="登录密码">
          <el-input v-model="form.passWord" type="Password" />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="form.newpassWord" type="Password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPawssdVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveForm(3)">确 定</el-button>
      </div>
    </el-dialog>

    <!--修改角色-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialoRoleVisible"
      width="60%"
      :before-close="handleClose"
      :show-close="false"
    >
      <el-form :model="form" :inline="true" label-position="right">
        <el-form-item label="登录名称">
          <span readonly v-html="form.loginName" />
        </el-form-item>
        <el-form-item label="员工账户(昵称)">
          <span readonly v-html="form.nickName" />
        </el-form-item>
        <br />
        <el-form-item label="角色">
          <el-checkbox
            v-for="role in rolelist"
            :key="role.id"
            v-model="role.ischeck"
            :label="role.roleName"
            @change="rolechange($event, role.id)"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialoRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveForm(2)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { AjaxToken } from "@/api/common";
import { AjaxGet } from "@/api/common";
import { SelectAjax } from "@/api/common";
import { TipMsg } from "@/api/common";
import sessionStorage from "@/api/Storage";
import "url-search-params-polyfill";
import PinYinMatch from "pinyin-match";
export default {
  name: "Manager",
  components: { Pagination },
  data() {
    return {
      loginid: "",
      logincpnid:"",
      rolelist: [],
      selectrolelist: [],
      formLabelWidth: "120px",
      MngrbaseinfoData: null,
      multipleSelection: [],
      cpnoptions: [],
      listQuery: {
        title: "",
        total: 0,
        page: 1,
        limit: 10,
      },
      selectparms: {
        cpnID: "",
      },
      listLoading: true,
      dialogFormVisible: false,
      dialoRoleVisible: false,
      dialogPawssdVisible: false,
      dialogInfoVisible: false,
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "添加",
      },
      form: {
        iD: "",
        loginName: "",
        passWord: "",
        newpassWord: "",
        nickName: "",
        state: "",
        createTime: "",
        isDeleted: "",
        lastLoginIP: "",
        lastLoginTime: "",
        thisLoginIP: "",
        thisLoginTime: "",
        loginNumber: "",
        cpnId: "system",
        tel: "",
        email: "",
      },
      details_form: {
        iD: "",
        loginName: "",
        passWord: "",
        nickName: "",
        state: "",
        createTime: "",
        isDeleted: "",
        lastLoginIP: "",
        lastLoginTime: "",
        thisLoginIP: "",
        thisLoginTime: "",
        loginNumber: "",
        cpnId: "",
        tel: "",
        email: "",
      },
    };
  },
  mounted() {
    var userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
    this.logincpnid = userinfo.cpnId;
    this.loginid=sessionStorage.getItem("id");
    backstage.GeCpntListItems(this);
  },
  created() {
    var userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
    this.logincpnid = userinfo.cpnId;
     this.loginid=sessionStorage.getItem("id");
    this.fetchData();
    backstage.GeCpntListItems(this);
  },
  methods: {
     cpnmatch(val) {
      if (val) {
        let result = [];
        this.cpnoptions.forEach((item) => {
          let matchRes = PinYinMatch.match(item.label, val);
          if (matchRes) {
            result.push(item);
          }
        });
        this.cpnoptions = result;
      } else {
        this.cpnid = "";
        this.cpnoptions = backstage.GeCpntListItems(this);
      }
    },

    handleClose() {},
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    rolechange(e, id) {
      if (e) {
        if (this.selectrolelist.length <= 0) {
          this.selectrolelist.push({ RoleId: id });
        } else {
          this.selectrolelist.forEach((element) => {
            if (element.RoleId != id) {
              this.selectrolelist.push({ RoleId: id });
            }
          });
        }
      } else {
        var truerolelist = [];
        this.selectrolelist.forEach((element) => {
          if (element.RoleId != id) {
            truerolelist.push(element);
          }
        });
        this.selectrolelist = truerolelist;
      }
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.fetchData();
    },
    handleCreate() {
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      (this.form = {
        iD: "",
        loginName: "",
        passWord: "",
        newpassWord: "",
        nickName: "",
        state: "",
        createTime: "",
        isDeleted: "",
        lastLoginIP: "",
        lastLoginTime: "",
        thisLoginIP: "",
        thisLoginTime: "",
        loginNumber: "",
        cpnId: "system",
        tel: "",
        email: "",
      }),
        backstage.GeCpntListItems(this);
      backstage.LoadMangerRoleList(this, "");
    },
    deleteClick(row) {
      this.listLoading = true;
      var multis = [];
      var params = new URLSearchParams();
      if (row == undefined || row == "") {
        var arr = this.multipleSelection;
        if (arr == undefined || arr.length <= 0) {
          this.$message({
            showClose: true,
            message: "请至少选中一行",
            type: "error",
          });
          this.listLoading = false;
          return;
        } else {
          for (var i = 0; i < arr.length; i++) {
            multis.push(arr[i].id);
          }
          params.append("delds", JSON.stringify(multis));
        }
      } else {
        multis.push(row.id);
        params.append("delds", JSON.stringify(multis));
      }
      this.$confirm("确认删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then((a) => {
          this.listLoading = true;
          backstage.DelManager(this, params);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          this.listLoading = false;
        });
    },
    handleClick(row, type) {
      this.selectrolelist = [];
      this.dialogStatus = "update";
      this.form.loginName = row.loginName;
      this.form.nickName = row.nickName;
      this.form.iD = row.id;
      backstage.LoadMangerRoleList(this, row.id);
      if (type == 1) {
        // 修改信息
        this.dialogInfoVisible = true;
      } else if (type == 2) {
        // 修改角色
        this.dialoRoleVisible = true;
      }
      if (type == 3) {
        // 修改密码
        this.dialogPawssdVisible = true;
      }
    },
    saveForm(type) {
      if (this.form.loginName == "" && (type == 0 || type == 1)) {
        return TipMsg(this, "请输入登录名");
      } else if (this.form.nickName == "" && (type == 0 || type == 1)) {
        return TipMsg(this, "请输入昵称");
      } else if (this.form.passWord == "" && (type == 0 || type == 3)) {
        return TipMsg(this, "请输入密码");
      } else if (this.form.passWord.length < 6 && (type == 0 || type == 3)) {
        return TipMsg(this, "密码至少6位");
      } else if (this.form.cpnId == "" && (type == 0 || type == 1)) {
        return TipMsg(this, "请选择企业");
      } else if (
        this.form.passWord != this.form.newpassWord &&
        (type == 0 || type == 3)
      ) {
        return TipMsg(this, "两次密码不一致,请重试");
      } else if (this.selectrolelist.length <= 0 && (type == 0 || type == 2)) {
        return TipMsg(this, "请至少选择一个角色");
      }
      var params = new URLSearchParams();
      params.append("ID", this.form.iD);
      params.append("LoginName", this.form.loginName);
      params.append("NickName", this.form.nickName);
      params.append("PassWord", this.form.passWord);
      params.append("typ", type);
      params.append("CpnId", this.form.cpnId);
      params.append("roles", JSON.stringify(this.selectrolelist));
      backstage.AddMangerBaseInfo(this, params);
    },
    fetchData() {
      this.listLoading = true;
      // 搜索
      var params = new URLSearchParams();
      params.append(
        "Parms",
        '{"page":' +
          this.listQuery.page +
          ',"rows":' +
          this.listQuery.limit +
          "}"
      );
      params.append("Name", this.listQuery.title);
      params.append("CpnId", this.selectparms.cpnID);

      backstage.GetManagerList(this, params);
    },
  },
};
// 后台事件
var backstage = {
  // 获取Mngrbaseinfo集合
  GetManagerList: function (thisobj, params) {
    AjaxToken(
      thisobj,
      "GetManagerList",
      params,
      "post",
      function (res) {
        var body = res.data.data;
        thisobj.MngrbaseinfoData = body.rows;
        thisobj.listQuery.page = body.page;
        thisobj.listQuery.total = body.records;
        thisobj.listLoading = false;
      },
      function (err) {}
    );
  },
  LoadMangerRoleList: function (thisobj, id) {
    AjaxGet(
      thisobj,
      "LoadMangerRoleList?id=" + id + "",
      function (res) {
        var body = res.data.data;
        thisobj.rolelist = body;
        thisobj.rolelist.forEach((element) => {
          if (element.ischeck) {
            thisobj.selectrolelist.push({ RoleId: element.id });
          }
        });
      },
      function (err) {}
    );
  },
  AddMangerBaseInfo: function (thisobj, params) {
    AjaxToken(
      thisobj,
      "AddMangerBaseInfo",
      params,
      "post",
      function (res) {
        var body = res.data;
        if (body.success) {
          thisobj.$message({
            showClose: true,
            message: body.message,
            type: "success",
            duration: 2000,
          });
          thisobj.fetchData();
          thisobj.dialogFormVisible = false;
          thisobj.dialoRoleVisible = false;
          thisobj.dialogInfoVisible = false;
          thisobj.dialogPawssdVisible = false;
        } else {
          thisobj.$message({
            showClose: true,
            message: body.message,
            type: "error",
          });
        }
      },
      function (err) {}
    );
  },
  DelManager: function (thisobj, params) {
    AjaxToken(
      thisobj,
      "DelManager",
      params,
      "post",
      function (res) {
        thisobj.listLoading = true;
        var body = res.data;
        if (body.success) {
          thisobj.$message({
            showClose: true,
            message: body.message,
            type: "success",
            duration: 2000,
          });
          thisobj.fetchData();
          thisobj.dialogFormVisible = false;
        } else {
          thisobj.$message({
            showClose: true,
            message: body.message,
            type: "error",
          });
        }
      },
      function (err) {}
    );
  },
  GeCpntListItems: function (thisobj) {
    SelectAjax(
      "GeCpntListItems?val=" + thisobj.logincpnid + "",
      function (response) {
        var body = response.data;
        thisobj.cpnoptions = [];
        body.data.forEach((element) => {
          thisobj.cpnoptions.push({
            value: element.value,
            label: element.text,
          });
        });
      },
      function (error) {}
    );
  },
};
</script>

